﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace CoNatural.Data.VisualStudio.AddIn.Controls {
   public partial class SelectNamingConventionsControl : UserControl {
      public SelectNamingConventionsControl() {
         InitializeComponent();
      }

		public void Initialize(IEnumerable<Model.DbObject> dbObjects, bool genareDotSqlVisible) {
			generateDotSql.Visible = genareDotSqlVisible;
			generateDotSql.Checked = false;
			dbObjectBindingSource.DataSource = dbObjects;
         BuildCommandNames();
      }

      private void refreshButton_Click(object sender, EventArgs e) {
         BuildCommandNames();
      }

		public bool GenerateSqlFile { get { return generateDotSql.Checked; } }

      private void BuildCommandNames() {
         string[] skips = skipPartsTextBox.Text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
         foreach (Model.DbObject sp in dbObjectBindingSource) {
            StringBuilder sb = new StringBuilder();
            // include schema in namespace
            if (includeSchemaCheckBox.Checked)
               sb.Append(sp.Schema);

            if (namespaceSeparatorTextBox.Text.Length == 0) {
               if (sb.Length > 0)
                  sb.Append(".");
               sb.Append(sp.Name);
            }
            else {
               // break stored procedure name into parts to build namespace (skip parts if necessary)
               string[] parts = sp.Name.Split(new string[] { namespaceSeparatorTextBox.Text }, StringSplitOptions.RemoveEmptyEntries);
               for (int i = 0; i < parts.Length; i++) {
                  if (skips.Length > 0) {
                     bool skipit = false;
                     foreach (string skip in skips)
                        if (skip == i.ToString()) {
                           skipit = true;
                           break;
                        }
                     if (skipit)
                        continue;
                  }
                  if (sb.Length > 0)
                     sb.Append(".");
                  sb.Append(parts[i]);
               }
            }
            // save name
            sp.CommandName = sb.ToString();
         }
         dataGridView1.Refresh();
      }
   }
}
